package servlet;

import com.geepi.base.DBUtil;
import model.Article;
import model.ArticleListInfo;
import model.BasseInfo;
import model.PageInfo;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class CollectResourceServlet extends HttpServlet {

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * Constructor of the object.
	 */
	public CollectResourceServlet() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		int pagesize = Integer.parseInt(request.getParameter("pagesize"));
		int pagenum = Integer.parseInt(request.getParameter("pagenum"));
		String account = request.getParameter("account");
		String token = request.getParameter("token");
		int status = -1;
		String message = "";
		int totalPage = -1;
		ArticleListInfo articleListInfo = new ArticleListInfo();

		if (!token.equals("cf7cbe86-270f-4735-82ef-23709a07c249")) {
			status = 100;
			message = "接口验证失败";
		} else {						
			try {
				int startCount = (pagenum - 1) * pagesize;
				String querySql = String.format("select * from resource , favorites where account = '%s' and resource.id = favorites.resourceId;", account);
				String queryCountSql = "select count(*) from resource;";
				
				DBUtil dbUtil = new DBUtil();
				boolean isOpen = dbUtil.open();
				if (isOpen == false) {
					status = 102;
					message = "数据库打开失败";
				} else {
					ResultSet resultSetCount = dbUtil.query(queryCountSql);
					while (resultSetCount.next()) {
						String tempStr = resultSetCount.getString(1);
						int totalCount = Integer.parseInt(tempStr);
						totalPage = totalCount / pagesize + 1;
					}
				
					ResultSet rs = dbUtil.query(querySql);

					String resourceId = "";
			        
			        if (rs == null) {
			        	status = 101;
			        	message = "没查到数据";
			        } else {
						List<Article> articleList = new ArrayList<>();
						while (rs.next()) {
							resourceId = rs.getString(1);
							//声明一个Hash对象并添加数据
							Article article = new Article();
							article.setId(resourceId);
							article.setTitle(rs.getString("title"));
							article.setType(rs.getString("type"));
							article.setAuthor(rs.getString("author"));
							article.setCreatetime(rs.getString("createtime"));

							String dsc = rs.getString("dsc");
							if (dsc == null || dsc.equals("")) {
								//subrange from content
								String content = rs.getString("detailInfo");
								if (content.length() > 200) {
									dsc = content.substring(0, 200);
								} else {
									dsc = content;
								}
							}
							article.setDsc(dsc);
							articleList.add(article);
						}
						articleListInfo.setList(articleList);
						PageInfo pageInfo = new PageInfo();
						pageInfo.setPagenum(pagenum);
						pageInfo.setTotalpage(totalPage);
						articleListInfo.setPageInfo(pageInfo);
						status = 0;
						message = "接口验证成功";
			        }
				}

			} catch (SQLException e) {
				// TODO Auto-generated catch block
				status = 105;
				message = e.getMessage();
			} 
		}

		BasseInfo basseInfo = new BasseInfo();
		basseInfo.setStatus(status);
		basseInfo.setMsg(message);
		basseInfo.setItem(articleListInfo);
		JSONObject jsonObject = new JSONObject();
		jsonObject = JSONObject.fromObject(basseInfo);

		response.setContentType("application/json;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		out.println(jsonObject);
		out.flush(); // 必须有这行，不然页面不会显示
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		out.println("<HTML>");
		out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
		out.println("  <BODY>");
		out.print("    This is ");
		out.print(this.getClass());
		out.println(", using the POST method");
		out.println("  </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}
